package com.alamkanak.weekview.sample;

import com.alamkanak.weekview.DateTimeInterpreter;
import com.alamkanak.weekview.MonthLoader;
import com.alamkanak.weekview.WeekView;
import com.alamkanak.weekview.WeekViewEvent;
import com.alamkanak.weekview.sample.utils.ToastUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.RectFloat;
import ohos.agp.window.dialog.PopupDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class AsynchronousAbility extends Ability implements WeekView.EventClickListener,
        MonthLoader.MonthChangeListener, WeekView.EventLongPressListener,
        WeekView.EmptyViewLongPressListener {

    private static final int TYPE_DAY_VIEW = 1;
    private static final int TYPE_THREE_DAY_VIEW = 2;
    private static final int TYPE_WEEK_VIEW = 3;
    private int mWeekViewType = TYPE_THREE_DAY_VIEW;
    private WeekView mWeekView;

    private Image img;
    private Text titleName,titleToday,titleDayview;
    private PopupDialog popupDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        super.setUIContent(ResourceTable.Layout_slice_weekview);


        mWeekView = (WeekView) findComponentById(ResourceTable.Id_weekView);
        // Show a toast message about the touched event.
        mWeekView.setOnEventClickListener(this);
        // The week view has infinite scrolling horizontally. We have to provide the events of a
        // month every time the month changes on the week view.
        mWeekView.setMonthChangeListener(this);
        // Set long press listener for events.
        mWeekView.setEventLongPressListener(this);
        // Set long press listener for empty view
        mWeekView.setEmptyViewLongPressListener(this);
        // Set up a date time interpreter to interpret how the date and time will be formatted in
        // the week view. This is optional.
        setupDateTimeInterpreter(false);

        titleName = (Text) findComponentById(ResourceTable.Id_title_name);
        titleToday = (Text) findComponentById(ResourceTable.Id_title_today);
        titleDayview = (Text) findComponentById(ResourceTable.Id_title_dayview);
        img = (Image) findComponentById(ResourceTable.Id_title_img);

        titleName.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        titleName.setText("Asynchronous Events");

        titleToday.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mWeekView.goToToday();
            }
        });

        titleDayview.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mWeekViewType != TYPE_DAY_VIEW) {
                    mWeekViewType = TYPE_DAY_VIEW;
                    mWeekView.setNumberOfVisibleDays(1);

                    setDayView();
                }
            }
        });

        img.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                popupDialog  = new PopupDialog(getContext(),img);
                Component layout = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_dialog_menu,null,false);
                Component dayview =  layout.findComponentById(ResourceTable.Id_menu_3dayview_layout);
                Component weekview =  layout.findComponentById(ResourceTable.Id_menu_weekview_layout);
                dayview.setClickedListener(clickedListener);
                weekview.setClickedListener(clickedListener);

                Checkbox dayviewBox = (Checkbox) layout.findComponentById(ResourceTable.Id_menu_3dayview);
                Checkbox weekviewBox = (Checkbox) layout.findComponentById(ResourceTable.Id_menu_weekview);

                if(mWeekViewType == TYPE_WEEK_VIEW){
                    dayviewBox.setChecked(false);
                    weekviewBox.setChecked(true);
                }else if(mWeekViewType == TYPE_THREE_DAY_VIEW){
                    dayviewBox.setChecked(true);
                    weekviewBox.setChecked(false);
                }else{
                    dayviewBox.setChecked(false);
                    weekviewBox.setChecked(false);
                }

                dayviewBox.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
                    @Override
                    public void onCheckedChanged(AbsButton absButton, boolean b) {

                        popupDialog.hide();
                        if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
                            mWeekViewType = TYPE_THREE_DAY_VIEW;
                            mWeekView.setNumberOfVisibleDays(3);

                            setDayView();
                        }

                    }
                });

                weekviewBox.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
                    @Override
                    public void onCheckedChanged(AbsButton absButton, boolean b) {

                        popupDialog.hide();
                        if (mWeekViewType != TYPE_WEEK_VIEW) {
                            mWeekViewType = TYPE_WEEK_VIEW;
                            mWeekView.setNumberOfVisibleDays(7);
                            setWeekView();
                        }
                    }
                });

                popupDialog.setCustomComponent(layout);
                popupDialog.setAutoClosable(true);
                popupDialog.show();

            }
        });

    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        terminateAbility();
    }

    @Override
    protected void onActive() {
        super.onActive();
        mWeekView.notifyDatasetChanged();
        ToastUtils.makeText(getContext(),"Could not download events from the internet");
    }

    //Lets change some dimensions to best fit the view.
    private void setDayView(){
        mWeekView.setColumnGap(24);
        mWeekView.setTextSize(35);
        mWeekView.setEventTextSize(34);
    }

    private void setWeekView(){
        mWeekView.setColumnGap(8);
        mWeekView.setTextSize(27);
        mWeekView.setEventTextSize(27);
    }

    Component.ClickedListener clickedListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component component) {
            switch (component.getId()){
                case ResourceTable.Id_menu_3dayview_layout:
                    popupDialog.hide();
                    if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
                        mWeekViewType = TYPE_THREE_DAY_VIEW;
                        mWeekView.setNumberOfVisibleDays(3);

                        setDayView();
                    }
                    break;
                case ResourceTable.Id_menu_weekview_layout:
                    popupDialog.hide();
                    if (mWeekViewType != TYPE_WEEK_VIEW) {
                        mWeekViewType = TYPE_WEEK_VIEW;
                        mWeekView.setNumberOfVisibleDays(7);

                        setWeekView();
                    }
                    break;
            }
        }
    };





    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
        // Populate the week view with some events.
        List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();

//        Calendar startTime = Calendar.getInstance();
//        startTime.set(Calendar.HOUR_OF_DAY, 3);
//        startTime.set(Calendar.MINUTE, 0);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        Calendar endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR, 1);
//        endTime.set(Calendar.MONTH, newMonth-1);
//        WeekViewEvent event = new WeekViewEvent(1, getEventTitle(startTime)+"=123456789"+"=123456789"+"=123456789"+"=123456789", startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_01));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.HOUR_OF_DAY, 3);
//        startTime.set(Calendar.MINUTE, 30);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.set(Calendar.HOUR_OF_DAY, 4);
//        endTime.set(Calendar.MINUTE, 30);
//        endTime.set(Calendar.MONTH, newMonth-1);
//        event = new WeekViewEvent(10, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_02));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.HOUR_OF_DAY, 4);
//        startTime.set(Calendar.MINUTE, 20);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.set(Calendar.HOUR_OF_DAY, 5);
//        endTime.set(Calendar.MINUTE, 0);
//        event = new WeekViewEvent(10, getEventTitle(startTime)+"=123456789", startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_03));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.HOUR_OF_DAY, 5);
//        startTime.set(Calendar.MINUTE, 30);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR_OF_DAY, 2);
//        endTime.set(Calendar.MONTH, newMonth-1);
//        event = new WeekViewEvent(2, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_02));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.HOUR_OF_DAY, 5);
//        startTime.set(Calendar.MINUTE, 0);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        startTime.add(Calendar.DATE, 1);
//        endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR_OF_DAY, 3);
//        endTime.set(Calendar.MONTH, newMonth - 1);
//        event = new WeekViewEvent(3, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_03));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.DAY_OF_MONTH, 15);
//        startTime.set(Calendar.HOUR_OF_DAY, 3);
//        startTime.set(Calendar.MINUTE, 0);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR_OF_DAY, 3);
//        event = new WeekViewEvent(4, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_04));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.DAY_OF_MONTH, 1);
//        startTime.set(Calendar.HOUR_OF_DAY, 3);
//        startTime.set(Calendar.MINUTE, 0);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR_OF_DAY, 3);
//        event = new WeekViewEvent(5, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_01));
//        events.add(event);
//
//        startTime = Calendar.getInstance();
//        startTime.set(Calendar.DAY_OF_MONTH, startTime.getActualMaximum(Calendar.DAY_OF_MONTH));
//        startTime.set(Calendar.HOUR_OF_DAY, 15);
//        startTime.set(Calendar.MINUTE, 0);
//        startTime.set(Calendar.MONTH, newMonth-1);
//        startTime.set(Calendar.YEAR, newYear);
//        endTime = (Calendar) startTime.clone();
//        endTime.add(Calendar.HOUR_OF_DAY, 3);
//        event = new WeekViewEvent(5, getEventTitle(startTime), startTime, endTime);
//        event.setColor(getColor(ResourceTable.Color_event_color_02));
//        events.add(event);

        return events;
    }



    //ResourceTable.Color_event_color_03
    public int getColor(int id){
        int color = -1;
        try {
            color = getResourceManager().getElement(id).getColor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return color;
    }

    @Override
    public void onEventClick(WeekViewEvent event, RectFloat eventRect) {
        ToastUtils.makeText(getContext(),"Clicked " + event.getName());
    }

    @Override
    public void onEventLongPress(WeekViewEvent event, RectFloat eventRect) {
        ToastUtils.makeText(getContext(),"Long pressed event: " + event.getName());
    }

    @Override
    public void onEmptyViewLongPress(Calendar time) {
        ToastUtils.makeText(getContext(),"Empty view long pressed: " + getEventTitle(time));
    }

    protected String getEventTitle(Calendar time) {
        return String.format("Event of %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH)+1, time.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * Set up a date time interpreter which will show short date values when in week view and long
     * date values otherwise.
     * @param shortDate True if the date values should be short.
     */
    private void setupDateTimeInterpreter(final boolean shortDate) {
        mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
            @Override
            public String interpretDate(Calendar date) {
                SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.getDefault());
                String weekday = weekdayNameFormat.format(date.getTime());
                SimpleDateFormat format = new SimpleDateFormat(" M/d", Locale.getDefault());

                // All xxx api level do not have a standard way of getting the first letter of
                // the week day name. Hence we get the first char programmatically.
                // Details: http://stackoverflow.com/questions/16959502/get-one-letter-abbreviation-of-week-day-of-a-date-in-java#answer-16959657
                if (shortDate)
                    weekday = String.valueOf(weekday.charAt(0));
                return weekday.toUpperCase() + format.format(date.getTime());
            }

            @Override
            public String interpretTime(int hour) {
                String result = hour == 0 ? "12 AM" : hour + " AM";
                return hour > 11 ? (hour - 12) + " PM" : result;
            }
        });
    }



}
